//
//  M_ArticleVC.swift
//  letuofu
//
//  Created by WH-JS on 2020/1/9.
//  Copyright © 2020 WH-JS. All rights reserved.
//

import UIKit
import MBProgressHUD
import WebKit

class QRCodeResultVC: BaseViewControllerWithHeader,WKUIDelegate,WKNavigationDelegate {
    lazy var backBtn : Button = {
        let v = self.drawRightButton(title: "返回")
        v.addTarget(self, action: #selector(fanhuiClick(btn:)), for: .touchUpInside)
        return v
    }()
    let webView = WKWebView()
    var artId = "" {
        didSet {
            if artId.count > 0 {
                loadUrl(ARTICLE_URL + artId)
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
    }
    
    
    override func _onBackButtonClick() {
        self.popViewController(vCount: 3)
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    // 进度条
    lazy var progressView:UIProgressView = {
        let progress = UIProgressView()
        progress.progressTintColor = UIColor.orange
        progress.trackTintColor = .clear
        return progress
    }()
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        //  加载进度条
            if keyPath == "estimatedProgress"{
                progressView.alpha = 1.0
                progressView.setProgress(Float((self.webView.estimatedProgress)), animated: true)
                if (self.webView.estimatedProgress)  >= 1.0 {
                    UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseOut, animations: {
                        self.progressView.alpha = 0
                    }, completion: { (finish) in
                        self.progressView.setProgress(0.0, animated: false)
                    })
                }
            }
        }
}

// MARK:- UI
extension QRCodeResultVC {
    func setupUI() {
//        headTitle.text = "活动推文"
        
        
        safeView.drawView(view: webView) { (make) in
            make.top.equalTo(headView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        webView.uiDelegate = self
        webView.navigationDelegate = self
        self.webView.addObserver(self, forKeyPath: "estimatedProgress", options: .old, context: nil)
        
        headView.drawView(view: progressView) { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.height.equalTo(2)
        }
    }
}

// MARK:- 事件
extension QRCodeResultVC {
    
    @objc func fanhuiClick(btn: Button) {
        popViewController()
    }
    
    func loadUrl(_ url : String) {
        let mapwayURL = URL(string: url)!
        let mapwayRequest = URLRequest(url: mapwayURL)
        webView.load(mapwayRequest)
    }
    
    func loadString(_ htmlString : String) {
        webView.loadHTMLString(htmlString, baseURL: nil)
    }
    
    ///WKUIDelegate,WKNavigationDelegate
    // 页面开始加载时调用
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!){
    }
    // 当内容开始返回时调用
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!){
    }
    // 页面加载完成之后调用
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
        /// 获取网页title
        self.title = self.webView.title
    }
    // 页面加载失败时调用
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error){
        /// 弹出提示框点击确定返回
//        let alertView = UIAlertController.init(title: "提示", message: "加载失败,并不是有效二维码！", preferredStyle: .alert)
//        let okAction = UIAlertAction.init(title:"确定", style: .default) { okAction in
//            _=self.navigationController?.popViewController(animated: true)
//        }
//        alertView.addAction(okAction)
//        self.present(alertView, animated: true, completion: nil)
        
    }
    
    ///WKUIDelegate,WKNavigationDelegate
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        let url = navigationAction.request.url
        print("url:\(String(describing: url)), host:\(String(describing: url?.host)), path:\(String(describing: url?.path)), query:\(String(describing: url?.query))")

        decisionHandler(.allow)
    }
}
